import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useTodoStore = defineStore('todo', () => {
  // 状态
  const todos = ref([])
  const categories = ref([]) // 存储所有分类
  const showCategories = ref([]) // 存储显示的分类
  const activeCategory = ref(null)

  // 计算属性
  const todosByCategory = computed(() => {
    const result = {}
    showCategories.value.forEach((category) => {
      result[category.id] = todos.value.filter((todo) => todo.labelId === category.id)
    })
    return result
  })

  const sortedShowCategories = computed(() => {
    return [...showCategories.value].sort((a, b) => a.order - b.order)
  })

  // 方法
  function addTodo(content, labelId, todoId) {
    todos.value.push({
      id: todoId,
      content,
      labelId: Number(labelId),
      completed: false,
      createdAt: new Date().toISOString(),
    })
  }

  // 从categories中删除分类
  function deleteCategory(categoryId) {
    const index = categories.value.findIndex((c) => c.id === categoryId)
    if (index !== -1) {
      categories.value.splice(index, 1)
    }

    // 同时也删除展示分类中的对应项
    deleteShowCategory(categoryId)
  }

  function toggleTodo(todoId) {
    const todo = todos.value.find((t) => t.id === todoId)
    if (todo) {
      todo.completed = !todo.completed
      // 确保更新时间信息
      todo.updatedAt = new Date().toISOString()
    }
  }

  function deleteTodo(todoId) {
    const index = todos.value.findIndex((t) => t.id === todoId)
    if (index !== -1) {
      todos.value.splice(index, 1)
    }
  }

  function updateTodoContent(todoId, newContent) {
    const todo = todos.value.find((t) => t.id === todoId)
    if (todo) {
      todo.content = newContent
      todo.updatedAt = new Date().toISOString()
    }
  }

  function setActiveCategory(categoryId) {
    const category = showCategories.value.find((cat) => cat.id === categoryId)
    activeCategory.value = category || null
  }

  function reorderShowCategories(categoryIds) {
    categoryIds.forEach((id, index) => {
      const category = showCategories.value.find((cat) => cat.id === id)
      if (category) {
        category.order = index
      }
    })
  }

  function addShowCategory(name, id) {
    const newCategoryId = id || Date.now()
    const newCategory = {
      id: newCategoryId,
      name,
      color: '#4361ee',
      order: showCategories.value.length,
    }
    showCategories.value.push(newCategory)
    return newCategoryId
  }

  function deleteShowCategory(categoryId) {
    const index = showCategories.value.findIndex((c) => c.id === categoryId)
    if (index !== -1) {
      showCategories.value.splice(index, 1)

      // 如果删除的是当前选中的分类，则清空选中
      if (activeCategory.value && activeCategory.value.id === categoryId) {
        activeCategory.value = null
      }
    }
  }

  function updateShowCategory(categoryId, name) {
    const category = showCategories.value.find((c) => c.id === categoryId)
    if (category) {
      category.name = name
    }
  }

  // 设置按标签分组的待办事项列表（从API获取）
  function setGroupedTodos(groupedData) {
    // 清空现有待办事项
    todos.value = []

    // 遍历分组数据，添加到todos中
    groupedData.forEach((group) => {
      group.todoItems.forEach((item) => {
        todos.value.push({
          id: item.todoItemId,
          content: item.content,
          labelId: group.labelId,
          labels: [group.labelId], // 默认将labelId添加到labels数组中
          completed: false,
          createdAt: item.createdAt,
          updatedAt: item.updatedAt,
        })
      })
    })
  }

  return {
    todos,
    categories,
    showCategories,
    activeCategory,
    sortedShowCategories,
    todosByCategory,
    setActiveCategory,
    addTodo,
    toggleTodo,
    deleteTodo,
    updateTodoContent,
    addShowCategory,
    deleteShowCategory,
    updateShowCategory,
    reorderShowCategories,
    setGroupedTodos,
    deleteCategory,
  }
})
